using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace WillStott.MxAppToolbox
{
    public class DirOps
    {
        public static string DeleteMatchingFiles(string path, string pattern)
        {
            string rc = "";
            try
            {
                if (path[path.Length - 1] == '\\')
                    path = path.Remove(path.Length - 1);
                DirectoryInfo dir = new DirectoryInfo(path);
                FileInfo[] files = dir.GetFiles(pattern);
                foreach (FileInfo file in files)
                    file.Delete();
            }
            catch (Exception ex)
            {
                rc = ex.Message;
            }
            return rc;
        }

        public static FileInfo[] GetFilesInDirectoryTree(string filePath)
        {
            string treeRoot = filePath;
            if (treeRoot[treeRoot.Length - 1] == '\\')
                treeRoot = treeRoot.Remove(treeRoot.Length - 1);
            List<FileInfo> list = new List<FileInfo>();
            RecurseDirectoryTree(list, treeRoot);
            FileInfo[] arr = new FileInfo[list.Count];
            list.CopyTo(arr);
            return arr;
        }

        private static void RecurseDirectoryTree(List<FileInfo> list, string filePath)
        {
            FileSystemInfo info = null;

            DirectoryInfo dir = new DirectoryInfo(filePath);
            FileSystemInfo[] items = dir.GetFileSystemInfos();
            foreach (FileSystemInfo item in items)
            {
                info = item;
                if (info is DirectoryInfo)
                    RecurseDirectoryTree(list, ((DirectoryInfo)info).FullName);
                FileInfo file = info as FileInfo;
                if (file != null)
                      list.Add(file);
            }
        }
    }
}
